package com.woniuxy.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.system.demol.entity.*;
import com.woniuxy.system.demol.vo.RoleADPermsVo;
import com.woniuxy.system.demol.vo.RoleAllVo;
import com.woniuxy.system.demol.vo.RoleUpdateVo;
import com.woniuxy.system.mapper.*;
import com.woniuxy.system.service.RolePermsService;
import com.woniuxy.system.service.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author why
 * @since 2023-09-08
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private RoleMapper roleMapper;

    @Resource
    private RolePermsService rolePermsService;
    @Resource
    private RolePermsMapper rolePermsMapper;

    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private SystemSectorMapper systemSectorMapper;


    @Override
    public Integer insertRole(Role newRole) {
        return roleMapper.insertRole(newRole);
    }

    @Override
    public Boolean insertSR(Integer sid, Integer reRid) {
        return roleMapper.insertSR(sid, reRid);
    }

  //  @GlobalTransactional
  @Transactional
    @Override
    public Boolean addDelPerms(RoleADPermsVo roleADPermsVo) {

        //获取aid
        Integer aid = roleADPermsVo.getAid();

        //获取rid
        Integer rid = roleADPermsVo.getRid();

        //修改角色的aid
        Role role = new Role().setId(rid).setAid(aid);
        int i = roleMapper.updateById(role);
        if (i == 1) {
            //删除原本的role_perms的表
            Map<String, Object> condition = new HashMap<String, Object>();
            condition.put("rid", rid);
            boolean b = rolePermsService.removeByMap(condition);
            if (b) {
                //批量插入数据
                List<RolePerms> rp = new ArrayList<>();
                //1遍历
                for (int j = 0; j < roleADPermsVo.getPid().size(); j++) {
                    RolePerms rolePerms = new RolePerms().setRid(rid).setPid(roleADPermsVo.getPid().get(j));
                    rp.add(rolePerms);
                }
                boolean b1 = rolePermsService.saveBatch(rp);
                if (b1) {
                    return true;
                }
            }

        }
        return false;
    }

    @Override
    public Map<String, Object> findAllRole(Integer offset, Integer pageSize) {
        List<RoleAllVo> pageList = roleMapper.findAllRole(offset, pageSize);
        for (int i = 0; i < pageList.size(); i++) {
            if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 1) {
                pageList.get(i).setDepartment("管理层");
            } else if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 2) {
                pageList.get(i).setDepartment("销售部门");
            } else if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 3) {
                pageList.get(i).setDepartment("财务部门");
            } else if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 4) {
                pageList.get(i).setDepartment("采购部门");
            } else if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 5) {
                pageList.get(i).setDepartment("仓库部门");
            } else if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 6) {
                pageList.get(i).setDepartment("产品部门");
            } else if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 7) {
                pageList.get(i).setDepartment("商务部门");
            }
            if (Integer.valueOf(pageList.get(i).getState()).intValue() == 1) {
                pageList.get(i).setStatus(false);
            } else if (Integer.valueOf(pageList.get(i).getState()).intValue() == 0) {
                pageList.get(i).setStatus(true);
            }


        }
        int totalCount = roleMapper.pageListCount();
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("pageList", pageList);
        result.put("totalCount", totalCount);
        return result;
    }

    @Override
    public int pageListCount() {
        return roleMapper.pageListCount();
    }

  //  @GlobalTransactional
  @Transactional
    @Override
    public Boolean addRole(RoleUpdateVo role) {
        //用于记录新生成的rid为多少
        Integer rid = 0;

        //1生成名字
        if (role.getIdentity() == 1) {
            //文员
            String y = getYBuilder();
            role.setName(y);
            //插入role表格
            Role role1 = new Role().setAid(role.getAid()).setName(y).setDescription(role.getDescription());
            roleMapper.insertRole(role1);
            rid = role1.getId();
        } else if (role.getIdentity() == 2) {
            //管理员
            String x = getXBuilder();
            role.setName(x);
            //插入role表格
            Role role1 = new Role().setAid(role.getAid()).setName(x).setDescription(role.getDescription());
            roleMapper.insertRole(role1);
            rid = role1.getId();
        }
        System.out.println("rid:" + rid);

        //生成时间
        SimpleDateFormat formatter = new SimpleDateFormat(" yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String format = formatter.format(date);
        //设置时间
        role.setTime(format);
        //在system_new_role表中插入信息
        roleMapper.addNewRole(role);

        //将权限拿出
        List<Integer> pid = new ArrayList<>();
        for (Integer i :
                role.getPermsList()) {
            pid.add(i);
        }
        for (Integer j :
                role.getSpPermsList()) {
            pid.add(j);
        }
        int num = 0;
        for (int i = 0; i < pid.size(); i++) {
            RolePerms rolePerms = new RolePerms().setRid(rid).setPid(pid.get(i));
            int insert = rolePermsMapper.insert(rolePerms);
            num += insert;
        }
        if (num == pid.size()) {
            roleMapper.addSSR(rid, role.getSid());
            return true;
        }


        return false;
    }

    @Override
    public Map<String, Object> findAllRole2(int offset, Integer pageSize) {
        List<RoleAllVo> pageList = roleMapper.findAllRole2(offset, pageSize);
        for (int i = 0; i < pageList.size(); i++) {
            if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 1) {
                pageList.get(i).setDepartment("管理层");
            } else if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 2) {
                pageList.get(i).setDepartment("销售部门");
            } else if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 3) {
                pageList.get(i).setDepartment("财务部门");
            } else if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 4) {
                pageList.get(i).setDepartment("采购部门");
            } else if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 5) {
                pageList.get(i).setDepartment("仓库部门");
            } else if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 6) {
                pageList.get(i).setDepartment("产品部门");
            } else if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 7) {
                pageList.get(i).setDepartment("商务部门");
            }
            if (Integer.valueOf(pageList.get(i).getState()).intValue() == 1) {
                pageList.get(i).setStatus(false);
            } else if (Integer.valueOf(pageList.get(i).getState()).intValue() == 0) {
                pageList.get(i).setStatus(true);
            }


        }
        int totalCount = roleMapper.pageListCount() - 13;
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("pageList", pageList);
        result.put("totalCount", totalCount);
        return result;
    }
    @Override
    public Map<String, Object> findAllRole3(int offset, Integer pageSize,Integer id) {
        User user = userMapper.selectById(id);
        List<RoleAllVo> pageList = new ArrayList<RoleAllVo>();
        int totalCount = 0 ;
        if (user.getSid().equals("1")){
            pageList = roleMapper.findAllRole3(offset, pageSize);
            totalCount =roleMapper.pageListCount3();
        }else{
            pageList =   roleMapper.findNewRole(offset, pageSize,Integer.valueOf(user.getSid()).intValue());
            totalCount=roleMapper.pageListCount6(Integer.valueOf(user.getSid()).intValue());
        }



        for (int i = 0; i < pageList.size(); i++) {
            if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 1) {
                pageList.get(i).setDepartment("管理层");
            } else if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 2) {
                pageList.get(i).setDepartment("销售部门");
            } else if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 3) {
                pageList.get(i).setDepartment("财务部门");
            } else if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 4) {
                pageList.get(i).setDepartment("采购部门");
            } else if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 5) {
                pageList.get(i).setDepartment("仓库部门");
            } else if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 6) {
                pageList.get(i).setDepartment("产品部门");
            } else if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 7) {
                pageList.get(i).setDepartment("商务部门");
            }
            if (Integer.valueOf(pageList.get(i).getState()).intValue() == 1) {
                pageList.get(i).setStatus(false);
            } else if (Integer.valueOf(pageList.get(i).getState()).intValue() == 0) {
                pageList.get(i).setStatus(true);
            }


        }

        Map<String, Object> result = new HashMap<String, Object>();
        result.put("pageList", pageList);
        result.put("totalCount", totalCount);
        return result;
    }
    @Override
    public Map<String, Object> findStateOpen(int offset, Integer pageSize) {
        List<RoleAllVo> pageList = roleMapper.findAll3(offset, pageSize);
        for (int i = 0; i < pageList.size(); i++) {
            if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 1) {
                pageList.get(i).setDepartment("管理层");
            } else if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 2) {
                pageList.get(i).setDepartment("销售部门");
            } else if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 3) {
                pageList.get(i).setDepartment("财务部门");
            } else if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 4) {
                pageList.get(i).setDepartment("采购部门");
            } else if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 5) {
                pageList.get(i).setDepartment("仓库部门");
            } else if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 6) {
                pageList.get(i).setDepartment("产品部门");
            } else if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 7) {
                pageList.get(i).setDepartment("商务部门");
            }
            if (Integer.valueOf(pageList.get(i).getState()).intValue() == 1) {
                pageList.get(i).setStatus(false);
            } else if (Integer.valueOf(pageList.get(i).getState()).intValue() == 0) {
                pageList.get(i).setStatus(true);
            }


        }

        int totalCount = roleMapper.pageListCount3();
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("pageList", pageList);
        result.put("totalCount", totalCount);
        return result;
    }

    @Override
    public Map<String, Object> findStateClose(int offset, Integer pageSize) {
        List<RoleAllVo> pageList = roleMapper.findAll4(offset, pageSize);
        for (int i = 0; i < pageList.size(); i++) {
            if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 1) {
                pageList.get(i).setDepartment("管理层");
            } else if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 2) {
                pageList.get(i).setDepartment("销售部门");
            } else if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 3) {
                pageList.get(i).setDepartment("财务部门");
            } else if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 4) {
                pageList.get(i).setDepartment("采购部门");
            } else if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 5) {
                pageList.get(i).setDepartment("仓库部门");
            } else if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 6) {
                pageList.get(i).setDepartment("产品部门");
            } else if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 7) {
                pageList.get(i).setDepartment("商务部门");
            }
            if (Integer.valueOf(pageList.get(i).getState()).intValue() == 1) {
                pageList.get(i).setStatus(false);
            } else if (Integer.valueOf(pageList.get(i).getState()).intValue() == 0) {
                pageList.get(i).setStatus(true);
            }


        }

        int totalCount = roleMapper.pageListCount4();
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("pageList", pageList);
        result.put("totalCount", totalCount);
        return result;
    }

    @Override
    public Map<String, Object> searchAll(Integer num, String input, int offset, Integer pageSize) {
        List<RoleAllVo> pageList = null;
        int totalCount = 0;
        if (num == 3) {
            totalCount = roleMapper.pageListCount1(input, offset, pageSize);
            pageList = roleMapper.searchAll(input, offset, pageSize);
        } else {
            pageList = roleMapper.searchAll2(num, input, offset, pageSize);
            totalCount = roleMapper.pageListCount2(num, input, offset, pageSize);
        }

        for (int i = 0; i < pageList.size(); i++) {
            if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 1) {
                pageList.get(i).setDepartment("管理层");
            } else if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 2) {
                pageList.get(i).setDepartment("销售部门");
            } else if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 3) {
                pageList.get(i).setDepartment("财务部门");
            } else if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 4) {
                pageList.get(i).setDepartment("采购部门");
            } else if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 5) {
                pageList.get(i).setDepartment("仓库部门");
            } else if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 6) {
                pageList.get(i).setDepartment("产品部门");
            } else if (Integer.valueOf(pageList.get(i).getSid()).intValue() == 7) {
                pageList.get(i).setDepartment("商务部门");
            }
            if (Integer.valueOf(pageList.get(i).getState()).intValue() == 1) {
                pageList.get(i).setStatus(false);
            } else if (Integer.valueOf(pageList.get(i).getState()).intValue() == 0) {
                pageList.get(i).setStatus(true);
            }


        }


        Map<String, Object> result = new HashMap<String, Object>();
        result.put("pageList", pageList);
        result.put("totalCount", totalCount);
        return result;
    }
  //  @GlobalTransactional
  @Transactional
    @Override
    public boolean updateRoleState(int i, String name,Integer id) {
        System.out.println("i:"+i);
        if (i==1){
            //先判断是否有账号使用该角色
            UserRole user = new UserRole().setRid(id);
            List<UserRole> userRoles = userRoleMapper.selectList(new QueryWrapper<>(user));
            System.out.println("userRoles:"+userRoles);
            //4.2遍历的到其中的uid
            if (!Objects.isNull(userRoles)) {
                System.out.println("进来了");
                for (int j = 0; j < userRoles.size(); j++) {
                    Integer uid = userRoles.get(j).getUid();
                    //根据uid查询user表，，获取里面的sid
                    User user1 = userMapper.selectById(uid);
                    String sid = user1.getSid();
                    //根据sid去获取该部门的名字
                    SystemSector systemSector = systemSectorMapper.selectById(Integer.valueOf(sid).intValue());
                    String name1 = systemSector.getName();
                    //根据名字去查询该角色对应的rid
                    Role role = roleMapper.selectByName(name1);
                    Integer id1 = role.getId();
                    //将user_role表中的数据修改了
                    UserRole userRole = new UserRole().setRid(id1);
                    userRoleMapper.update(userRole, new UpdateWrapper<UserRole>().eq("uid", uid));
                }
            }
        }



        return roleMapper.updateRoleState(i, name);
    }

    @Override
    public RoleAllVo findRoleByAccount(String account) {
        RoleAllVo roleByAccount = roleMapper.findRoleByAccount(account);
        if (roleByAccount == null) {
            RoleAllVo roleByName = roleMapper.findRoleByName(account);
            return roleByName;
        } else {
            return roleByAccount;
        }


    }
  //  @GlobalTransactional
  @Transactional
    @Override
    public Boolean updateRole(RoleUpdateVo role) {
        System.out.println(role);
        //根据id查找原本的信息
        RoleAllVo oldRole = roleMapper.findRoleById(role.getId());
        System.out.println(oldRole);
        //第一步，判断描述是否为空
        if (Objects.isNull(role.getDescription()) || role.getDescription() == "" || role.getDescription().length() == 0) {
            System.out.println("1");
            role.setDescription(oldRole.getDescription());
        } else {
            System.out.println("2");
            Role role1 = new Role().setDescription(role.getDescription());
            roleMapper.update(role1, new UpdateWrapper<Role>().eq("id", role.getId()));
        }
        //第二步，判断sid是否为空
        if (Objects.isNull(role.getSid())) {
            role.setSid(oldRole.getSid());
        }
        String name1 = null;
        //第三步，identity不为空
        if (!Objects.isNull(role.getIdentity())) {
            if (role.getIdentity() == 1) {
                String name = oldRole.getName();
                name = name.substring(0, name.length() - 1); // 剔除最后一个字符
                name1 = name + "y";
                role.setName(name1);
                Role role1 = new Role().setName(name1).setAid(role.getAid());
                roleMapper.update(role1, new UpdateWrapper<Role>().eq("id", role.getId()));
            } else {
                String name = oldRole.getName();
                name = name.substring(0, name.length() - 1); // 剔除最后一个字符
                name1 = name + "x";
                role.setName(name1);
                Role role1 = new Role().setName(name1).setAid(role.getAid());
                roleMapper.update(role1, new UpdateWrapper<Role>().eq("id", role.getId()));
            }
        }
        Integer id = role.getId();
        role.setId(oldRole.getId());
        role.setName(name1);
        roleMapper.updateRole(role);
        //第四步，sid不为空且与原本的sid不一致
        if (role.getSid() != oldRole.getSid()) {
            //4.1先判断是否有账号使用该角色，如果有，则将该账号的sid改为和本角色一致
            UserRole user = new UserRole().setRid(id);
            List<UserRole> userRoles = userRoleMapper.selectList(new QueryWrapper<>(user));
            //4.2遍历的到其中的uid
            if (userRoles != null) {
                for (int i = 0; i < userRoles.size(); i++) {
                    Integer uid = userRoles.get(i).getUid();
                    //修改user对应的部门id
                    User nuser = new User().setId(uid).setSid(String.valueOf(role.getSid()));
                    userMapper.updateById(nuser);
                }
            }
            //4.3如果两个perms不为空删除表中所有的角色权限对应
            if (!Objects.isNull(role.getPermsList()) || !Objects.isNull(role.getSpPermsList())) {
                //删除对应表
                Map<String, Object> condition = new HashMap<String, Object>();
                condition.put("rid", id);
                rolePermsMapper.deleteByMap(condition);
            }
            //4.4插入新的对应关系
            //将权限拿出
            List<Integer> pid = new ArrayList<>();
            for (Integer i :
                    role.getPermsList()) {
                pid.add(i);
            }
            for (Integer j :
                    role.getSpPermsList()) {
                pid.add(j);
            }
            for (int i = 0; i < pid.size(); i++) {
                RolePerms rolePerms = new RolePerms().setRid(id).setPid(pid.get(i));
                int insert = rolePermsMapper.insert(rolePerms);
            }
            //4.5将system_sector_role修改
            roleMapper.updateSSR(id, role.getSid());


        }

        return true;
    }
  //  @GlobalTransactional
  @Transactional
    @Override
    public Boolean delRole(Integer i, Integer rid) {
        //删除该角色
        //先判断是否有账号使用该角色
        UserRole user = new UserRole().setRid(rid);
        List<UserRole> userRoles = userRoleMapper.selectList(new QueryWrapper<>(user));
        //4.2遍历的到其中的uid
        if (userRoles != null) {
            for (int j = 0; j < userRoles.size(); j++) {
                Integer uid = userRoles.get(j).getUid();
               //根据uid查询user表，，获取里面的sid
                User user1 = userMapper.selectById(uid);
                String sid = user1.getSid();
                //根据sid去获取该部门的名字
                SystemSector systemSector = systemSectorMapper.selectById(Integer.valueOf(sid).intValue());
                String name = systemSector.getName();
                //根据名字去查询该角色对应的rid
                Role role = roleMapper.selectByName(name);
                Integer id = role.getId();
                //将user_role表中的数据修改了
                UserRole userRole = new UserRole().setRid(id);
                userRoleMapper.update(userRole, new UpdateWrapper<UserRole>().eq("uid", uid));
            }
        }
        //将表格中的角色状态改为3
        Role role1 = roleMapper.selectById(rid);
      Boolean c=  roleMapper.updateNewRoleDate(role1.getName(),i);
      if (c){
          return true;
      }
        return false;
    }




    //生成一个五位数的名字的方法x
    private static String getXBuilder() {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            char c = (char) (random.nextInt(26) + 'a'); // 随机生成一个小写字母
            sb.append(c);
        }
        sb.append('x'); // 最后一个字符为x
        String string = sb.toString();
        return string;
    }

    //生成一个五位数的名字的方法y
    private static String getYBuilder() {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            char c = (char) (random.nextInt(26) + 'a'); // 随机生成一个小写字母
            sb.append(c);
        }
        sb.append('y'); // 最后一个字符为y
        String string = sb.toString();
        return string;
    }


}
